<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Carousel</title>
  <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1">
</head>
<style>
  body {
    margin: 0;
    padding: 0;
  }

  .slide {
    display: flex;
    position: relative;
    left: 0;
  }

  .slide img {
    width: 100%;
    height: 250px;
  }

  .slide>div {
    width: 100%;
    flex-shrink: 0;
    height: 250px;
  }

  .carousel {
    overflow: hidden;
    width: 100%;
    height: 250px;
  }

  .contain {
    position: relative;
  }
</style>

<body>
  <div class="contain">
    <div class="carousel">
      <div class="slide">
        <img src="../images/img1.jpg" alt="">
        <img src="../images/img2.jpg" alt="">
        <img src="../images/img3.jpg" alt="">
      </div>
    </div>
  </div>
</body>
<script>
  var contain = document.querySelector('.contain');//获取需要改变left的元素
  var slide = document.querySelector('.slide');//获取需要改变left的元素
  var slideLength = slide.children.length + 2;//轮播图个数
  var timer = null;//定时器初始为null
  var currentIndex = 1;//当前索引
  var width = window.innerWidth;//屏幕宽度
  window.onload = function () {
    var everyTime = 2000;//轮播的间隔时间
    //实现无缝轮播需要在首尾分别添加一张图片，
    //使第二轮播放的时候能无缝衔接,这是无缝轮播的关键点。
    var firstDom = slide.firstElementChild.cloneNode(true);
    var lastDom = slide.lastElementChild.cloneNode(true);
    slide.appendChild(firstDom);
    slide.insertBefore(lastDom, slide.firstElementChild);
    slide.style.left = -width + 'px';
    autoPlay(everyTime);//页面打开后自动开启播放
    //自动播放
    function autoPlay (period) {
      timer = setInterval(function () {
        currentIndex++;
        //当移动到最后一张，也就是模拟的第一张
        if (currentIndex == slideLength - 1) {
          //首先清除原先的定时器
          clearInterval(timer);
          //处理临界情况
          criticality(1);
          //通次继续下一次轮播
          return autoPlay(period);
        } else {
          if (currentIndex < slideLength - 1) {
            play(-(width * currentIndex));
          }
        }
      }, period)
    }

    //轮播公共方法
    function play (left) {
      //1、图片移动left px；
      slide.style.left = left + 'px';
      slide.style.transition = 'left 1.5s';
    }
    function criticality (boundary) {
      //继续走临界的轮播
      play(-(width * currentIndex));
      //在轮播的同时将距离重置
      setTimeout(function () {
        slide.style.left = -width * boundary + 'px';
        slide.style.transition = 'left 0s';
        currentIndex = boundary;
      }, 1500);
    }
  }
</script>

</html>